package io;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable 
{
	private int _port;
	private ServerSocket _server;
	private Socket _socket;
	private Communicator _communicator;
	private ListenerManager _manager;
	
	public Communicator getCommunicator()
	{
		return _communicator;
	}
	
	public Server(int port, ListenerManager manager)
	{
		_port = port;
		_manager = manager;
	}
	
	@Override
	public void run()
	{
		try
		{
			_server = new ServerSocket(_port);
			_socket = _server.accept();
			_communicator = new Communicator(_socket, _manager);
			_communicator.execute();
			_socket.close();
			_server.close();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			if (_manager != null && _manager.getOnUnload() != null)
			{
				_manager.getOnUnload().onEventEDT(null);
			}
		}
	}
}
